import { exportFile } from 'sheetjs-tool'

const config = {
	baiduAPPID: '49210271',
	baiduAPI: 'CFbutaBw4ZQqPVY65kqV71ll',
	baiduSECRET: 'rYCpaqDNcM6WfCNtvGPc8Z4i68oZuk6U'
}
function getBaiduAuth() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'https://aip.baidubce.com/oauth/2.0/token',
			method: 'GET',
			data: {
				grant_type: 'client_credentials',
				client_id: config.baiduAPI,
				client_secret: config.baiduSECRET
			},
			header: {
				'Content-Type': 'application/json',
				Accept: 'application/json'
			}
		}).then(res => {
			resolve({ token: res.data.access_token })
		}).catch(c => reject(c))
	})
}

function getAccurateBank({ image, token }) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard?access_token=' + token,
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			data: {
				image
			}
		}).then(res => {
			const data = res.data
			resolve({ log_id: data.log_id, direction: data.direction, bankName: data.result.bank_name, bankCardNumber: data.result.bank_card_number })
		}).catch(c => reject(c))
	})
}

const columns = [
	{
		title: '日期',
		dataIndex: 'tallyTime'
	},
	{
		title: '账单类型',
		dataIndex: 'transactionType'
	},
	{
		title: '类目',
		dataIndex: 'icon'
	},
	{
		title: '金额',
		dataIndex: 'amount'
	},
	{
		title: '时间',
		dataIndex: 'meticulousTime'
	},
	{
		title: '备注',
		dataIndex: 'desc'
	}
]

function downLoadExcel(options, data = {}) {
	const fileName = data.fileName || '当月账单'
	exportFile({
		fileName: `${fileName}_${new Date().getTime()}.xlsx`,
		dataSource: options,
		columns
	})
}

export {
	getBaiduAuth,
	getAccurateBank,
	downLoadExcel
}